/**
 * May 14, 2014 2:03:35 PM
 */
package elitech.vietnam.copyweatherfashion.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
import elitech.vietnam.copyweatherfashion.R;

/**
 * @author Cong
 * 
 */
public class ExpandableTextView extends TextView implements View.OnClickListener {
	private static final int DEFAULT_TRIM_LENGTH = 200;
    private static final String ELLIPSIS = "...More";
 
    private CharSequence originalText;
    private CharSequence trimmedText;
    BufferType mType;
    private boolean trim = true;
    private int trimLength;
 
    public ExpandableTextView(Context context) {
        super(context, null);
        init(null);
    }
 
	public ExpandableTextView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
        init(attrs);
	}

	public ExpandableTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }
    
    private void init(AttributeSet attrs) {
    	if (attrs != null) {
	    	TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.ExpandableTextView);
	        this.trimLength = typedArray.getInt(R.styleable.ExpandableTextView_trimLength, DEFAULT_TRIM_LENGTH);
	        typedArray.recycle();
    	}
        setOnClickListener(this);
    }
 
    @Override
    public void setText(CharSequence text, BufferType type) {
        originalText = text;
        trimmedText = getTrimmedText(text);
        mType = type;
        super.setText((originalText != null && originalText.length() > trimLength) ? trimmedText : originalText, type);
    }
 
    private CharSequence getTrimmedText(CharSequence text) {
        if (originalText != null && originalText.length() > trimLength) {
        	SpannableString string = new SpannableString(originalText.subSequence(0, trimLength + 1) + ELLIPSIS);
        	string.setSpan(new UnderlineSpan(), trimLength + 4, trimLength + 8, 0);
        	string.setSpan(new ForegroundColorSpan(Color.BLUE), trimLength + 4, trimLength + 8, 0);
        	return string;
//            return new SpannableStringBuilder(originalText, 0, trimLength + 1).append(ELLIPSIS);
        } else {
            return originalText;
        }
    }
 
    public CharSequence getOriginalText() {
        return originalText;
    }
 
    public int getTrimLength() {
        return trimLength;
    }

	@Override
	public void onClick(View v) {
		trim = !trim;
		super.setText((trim) ? trimmedText : originalText, mType);
	}
}
